package com.example.player.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.viewpager.widget.ViewPager;
import androidx.appcompat.widget.Toolbar;

import android.app.AlertDialog;
import android.content.ClipData;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.easefun.polyvsdk.player.abi.BuildConfig;
import com.easefun.polyv.mediasdk.player.*;

import com.easefun.polyvsdk.PolyvSDKClient;
import com.easefun.polyvsdk.sub.vlms.entity.PolyvVlmsCoursesInfo;
import com.easefun.polyvsdk.sub.vlms.entity.PolyvVlmsDataBody;
import com.easefun.polyvsdk.sub.vlms.listener.PolyvVlmsApiListener2;
import com.easefun.polyvsdk.sub.vlms.main.PolyvVlmsManager2;
import com.easefun.polyvsdk.sub.vlms.main.PolyvVlmsTestData;
import com.easefun.polyvsdk.video.PolyvVideoView;
import com.example.player.PolyvIdUtil;
import com.example.player.PolyvPermission;
import com.example.player.PolyvSPUtils;
import com.example.player.PolyvSimpleSwipeRefreshLayout;
import com.example.player.adapter.HotCourseGridViewAdapter;
import com.example.player.adapter.LoopAdapter;
import com.example.player.listener.pagerOnClickListener;
import com.example.player.R;
import com.google.android.material.navigation.NavigationView;

import java.security.Permission;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    //轮播图使用的
    private ViewPager viewPager;
    private int[] mImg;
    private int[] mImg_id;
    private String[] mDec;
    private ArrayList<ImageView> mImgList;
    private LinearLayout dot_container;
    private TextView loop_dec;
    private int previousSelectedPosition=0;
    boolean isRunning =false;
    private DrawerLayout mDrawerLayout;

    //推荐页面
    public static final String IS_VLMS_ONLINE="isVlmsOnline";
    //hot course's GridView
    private GridView gv_hc;
    private HotCourseGridViewAdapter adapter;
    private List<PolyvVlmsCoursesInfo> lists;

    //online video btn ,upload btn,download btn
    private ImageView iv_online,iv_upload,iv_download;
    //title
    private TextView tv_title;

    //loading component
    private ProgressBar pb_loading;
    //empty data controller,reload
    private TextView tv_empty,tv_reload;
    //pull refresh controller
    private PolyvSimpleSwipeRefreshLayout srl_bot;
    private TextView tv_guide;
    private PolyvVlmsManager2 vlmsManager2;
    private PolyvPermission polyvPermission = null;

    private PolyvVlmsCoursesInfo course = null;

    private String Secret="XNeIt2plaWS+GkVNG/yeLXOSyiPc1qmXgY1xPhqw1hro97JiQi7RFr4vWpnxXmiMctKc656Sa0ahky3DOEuFVydeZBZPgncngFUvTzqBqAM0zEYMIkNBT7OjQVscokt5lBn43/iG++OOuCb3CWr2Hg==";
    private String Key="shSAYeZMQCjlDtw3";
    private String Vector="wqsmUMtp9PRWdjIx";

    private void findIdAndNew() {
        gv_hc=(GridView) findViewById(R.id.gv_hc);
        tv_title=(TextView) findViewById(R.id.tv_title);
        iv_online=(ImageView) findViewById(R.id.online_video);
        iv_upload=(ImageView) findViewById(R.id.upload);
        iv_download=(ImageView) findViewById(R.id.history);//history就是download 的内容
        pb_loading=(ProgressBar) findViewById(R.id.pg_bar);
        tv_empty=(TextView) findViewById(R.id.tv_empty);
        tv_reload=(TextView) findViewById(R.id.tv_reload);
        srl_bot=(PolyvSimpleSwipeRefreshLayout) findViewById(R.id.srl_bot);
//        tv_guide=(TextView) findViewById(R.id.tv_guide);//这个地方暂时没有加上那条热门课程的guide title
        lists=new ArrayList<>();

        vlmsManager2=new PolyvVlmsManager2(this);
    }

    private void getCoursesDetail() {
        vlmsManager2.getCourses2(1, 100, new PolyvVlmsApiListener2<PolyvVlmsDataBody<PolyvVlmsCoursesInfo>>() {
            @Override
            public void onFailed(Throwable throwable) {
                throwable.printStackTrace();
                pb_loading.setVisibility(View.GONE);
                tv_empty.setVisibility(View.GONE);
                tv_reload.setVisibility(View.GONE);
                srl_bot.setRefreshing(false);

                srl_bot.setEnabled(false);
                tv_reload.setVisibility(View.VISIBLE);
                if(MainActivity.this.lists.size()>0) {
                    MainActivity.this.lists.clear();
                    adapter.notifyDataSetChanged();
                }
                Log.d("TAG", "onFailed() returned: failed" );
            }

            @Override
            public void onSuccess(PolyvVlmsDataBody<PolyvVlmsCoursesInfo> data) {
                pb_loading.setVisibility(View.GONE);
                tv_empty.setVisibility(View.GONE);
                tv_reload.setVisibility(View.GONE);
                srl_bot.setRefreshing(false);

                srl_bot.setEnabled(true);
                if(data == null||data.getContents().size()==0) {
                    tv_empty.setVisibility(View.VISIBLE);
                    return;
                }
                MainActivity.this.lists.clear();
                MainActivity.this.lists.addAll(data.getContents());
                adapter.notifyDataSetChanged();
                Log.d("TAG", "onSuccess: Success getCourseDetail()");
            }
        });
    }



    private void initView(){
        if(PolyvVlmsTestData.USERID_2.equals(PolyvSDKClient.getInstance().getUserId()) ||
                PolyvVlmsTestData.USERID.equals(PolyvSDKClient.getInstance().getUserId())){
            getCoursesDetail();
            Log.d("start init", "initView() called走的if语句");
        } else {

            Log.d("start init", "initView() if->else");
            srl_bot.setVisibility(View.VISIBLE);

            //tv_guide.setVisibility(View.GONE);
            //tv_guide.setText(PolyvSDKClient.getInstance().getUserId());
        }
        adapter = new HotCourseGridViewAdapter(this,lists);

        gv_hc.setAdapter(adapter);
        gv_hc.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                course = lists.get(position);
                //permission
                polyvPermission.applyPermission(MainActivity.this,PolyvPermission.OperationType.playAndDownload);
            }
        });
        srl_bot.setColorSchemeResources(android.R.color.holo_blue_light,android.R.color.holo_red_light,
                android.R.color.holo_orange_light,android.R.color.holo_green_light);
        srl_bot.setEnabled(false);
        srl_bot.setChildView(gv_hc);

        srl_bot.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getCoursesDetail();
            }
        });
//        if(iv_online==null) {
//            Log.e("iv_online", "initView: iv_online is null");
//            iv_online=(ImageView)findViewById(R.id.online_video);
//            System.out.println((iv_online==null)?"kongde":"feikong");
//        }
//        if(iv_upload==null) {
//            Log.e("iv_upload", "initView: iv_upload is null");
//        }
//        if(iv_download==null) {
//            Log.e("iv_upload", "initView: iv_download is null");
//        }
//        iv_online.setOnClickListener(this);
//        iv_upload.setOnClickListener(this);
//        iv_download.setOnClickListener(this);
//        tv_reload.setOnClickListener(this);
//        tv_title.setOnClickListener(this);

    }
    public void initClient() {
        PolyvSDKClient client = PolyvSDKClient.getInstance();
        client.settingsWithConfigString(Secret,Key,Vector);
        client.initSetting(getApplicationContext());
        client.setViewerId("");
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);

        findIdAndNew();
        initView();
        Log.d("init", "onCreate().initView() returned: "  );

        polyvPermission=new PolyvPermission();
        polyvPermission.setResponseCallback(new PolyvPermission.ResponseCallback() {
            @Override
            public void callback(@NonNull PolyvPermission.OperationType type) {
                gotoActivity(type.getNum());
            }
        });

        Toolbar toolbar=(Toolbar)findViewById(R.id.toolbar);

        setSupportActionBar(toolbar);

        mDrawerLayout=(DrawerLayout)findViewById(R.id.drawer_layout);

        ActionBar actionBar=getSupportActionBar();
        if(actionBar!=null){
            actionBar.setDisplayHomeAsUpEnabled(true);
            //actionBar.setHomeAsUpIndicator(R.drawable.polyv_menu);
        }

        NavigationView navigationView=(NavigationView)findViewById(R.id.navView);

        navigationView.setCheckedItem(R.id.online_video);

        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch(item.getItemId()) {
                    case R.id.online_video:
                        startActivity(new Intent(MainActivity.this,PlayerActivity.class));
                        break;
                    case R.id.history:
                        mDrawerLayout.closeDrawers();
                        break;
                    case R.id.upload:
                        Log.i("TAG", "onNavigationItemSelected: please upload your video");
                        break;
                    case R.id.server:
                        Log.i("TAG", "onNavigationItemSelected: you are calling for help");
                        break;
                }
                return true;
            }
        });

        initLoopView();

        initClient();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    public boolean onCreateOptionsMenu(Menu menu){
        getMenuInflater().inflate(R.menu.toolbar,menu);
        return true;
    }
    private void initLoopView(){
        viewPager = (ViewPager)findViewById(R.id.loopviewpager);
        dot_container=(LinearLayout)findViewById(R.id.dot_loop);
        loop_dec=(TextView)findViewById(R.id.loop_desc);

        mImg=new int[]{
                R.drawable.test3,
                R.drawable.test3,
                R.drawable.test3,
                R.drawable.test3,
                R.drawable.test3
        };

        mDec=new String[]{
                "Pic1广告位招租",
                "Pic2广告位招租",
                "Pic3广告位招租",
                "Pic4广告位招租",
                "Pic5广告位招租",
        };
        mImg_id=new int[]{
                R.id.pager_img1,
                R.id.pager_img2,
                R.id.pager_img3,
                R.id.pager_img4,
                R.id.pager_img5
        };

        mImgList = new ArrayList<ImageView>();
        ImageView imageView;
        View dotView;
        LinearLayout.LayoutParams layoutParams;
        for(int i=0;i<mImg.length;i++){
            imageView = new ImageView(this);
            imageView.setBackgroundResource(mImg[i]);
            imageView.setId(mImg_id[i]);
            imageView.setOnClickListener(new pagerOnClickListener(getApplicationContext()));
            mImgList.add(imageView);

            dotView=new View(this);
            dotView.setBackgroundResource(R.drawable.dot);
            layoutParams=new LinearLayout.LayoutParams(10,10);
            if(i!=0){
                layoutParams.leftMargin=10;
            }
            dotView.setEnabled(false);
            dot_container.addView(dotView,layoutParams);
        }
        dot_container.getChildAt(0).setEnabled(true);
        loop_dec.setText(mDec[0]);
        previousSelectedPosition=0;
        viewPager.setAdapter(new LoopAdapter(mImgList));

        int m=(Integer.MAX_VALUE/2)%mImgList.size();
        int currentPosition=Integer.MAX_VALUE/2 - m;
        viewPager.setCurrentItem(currentPosition);


        final ViewPager.OnPageChangeListener pageChangeListener=new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                int newPosition=position%mImgList.size();
                loop_dec.setText(mDec[newPosition]);
                dot_container.getChildAt(previousSelectedPosition).setEnabled(false);
                dot_container.getChildAt(newPosition).setEnabled(true);
                previousSelectedPosition=newPosition;
                //System.out.println("this is selected------------");
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        };


        new Thread(){
            public void run(){
                isRunning = true;
                while(isRunning){
                    try{
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    //下一条
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            viewPager.setCurrentItem(viewPager.getCurrentItem()+1);
                            pageChangeListener.onPageSelected(viewPager.getCurrentItem()+1);
                        }
                    });
                }
            }
        }.start();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item){
        switch(item.getItemId()){
            case android.R.id.home:
                Log.d("TAG", "onOptionsItemSelected: click home");
                mDrawerLayout.openDrawer(GravityCompat.START);
                break;
            case R.id.setting:
                Log.d("TAG", "onOptionsItemSelected: you clicked setting");
                Toast.makeText(this,"you clicked setting",Toast.LENGTH_SHORT).show();
                break;
            default:
        }
        return true;
    }


    @Override
    public void onClick(View v) {
        Log.d("-------------", "onClick: ");
    }

    private void gotoSetSDKConfig() {
        final EditText etConfig = new EditText(this);
        new AlertDialog.Builder(this).setTitle("设置加密串")
                .setView(etConfig)
                .setPositiveButton("保存并重启", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        PolyvSPUtils.getInstance(MainActivity.this).put("SDKConfig", etConfig.getText().toString().trim(), true);
                        final Intent intent = MainActivity.this.getPackageManager().getLaunchIntentForPackage(MainActivity.this.getPackageName());
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(intent);
                        android.os.Process.killProcess(android.os.Process.myPid());
                    }
                }).setNegativeButton("取消",null)
                .setNeutralButton("课程配置并重启", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        PolyvSPUtils.getInstance(MainActivity.this).put("SDKConfig", PolyvVlmsTestData.CONFIG_2, true);
                        final Intent intent = MainActivity.this.getPackageManager().getLaunchIntentForPackage(MainActivity.this.getPackageName());
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(intent);
                        android.os.Process.killProcess(android.os.Process.myPid());
                    }
                })
                .show();
    }
    private void gotoActivity(int type) {
        PolyvPermission.OperationType OperationType = PolyvPermission.OperationType.getOperationType(type);
        switch (OperationType) {
            case readImei:
                PolyvSDKClient.getInstance().setImei(PolyvIdUtil.getAndroidId(this));
                break;
//            case play:
//                startActivity(new Intent(MainActivity.this, PolyvOnlineVideoActivity.class));
//                break;
//            case download:
//                startActivity(new Intent(MainActivity.this, PolyvDownloadActivity.class));
//                break;
//            case upload:
//                startActivity(new Intent(MainActivity.this, PolyvUploadActivity.class));
//                break;
//            case playAndDownload:
//                Intent intent = new Intent(MainActivity.this, PolyvPlayerActivity.class);
//                Bundle bundle = new Bundle();
//                bundle.putBoolean(MainActivity.IS_VLMS_ONLINE, true);
//                bundle.putString("course", course.toString());
//                intent.putExtras(bundle);
//                startActivity(intent);
//                break;
    }

    }
    /**
     * This is the method that is hit after the user accepts/declines the
     * permission you requested. For the purpose of this example I am showing a "success" header
     * when the user accepts the permission and a snackbar when the user declines it.  In your application
     * you will want to handle the accept/decline in a way that makes sense.
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(final int requestCode, String[] permissions, int[] grantResults) {
        if (polyvPermission.operationHasPermission(requestCode)) {
            gotoActivity(requestCode);
        } else {
            PolyvSDKClient.getInstance().setImei(PolyvIdUtil.getAndroidId(this));
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
                    if (!ActivityCompat.shouldShowRequestPermissionRationale(this, permissions[i])) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(this);
                        builder.setTitle("提示");
                        builder.setMessage("需要权限被拒绝，是否跳转到权限设置？");
                        builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                Toast.makeText(MainActivity.this, "点击权限，并打开全部权限", Toast.LENGTH_LONG).show();
                                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                intent.setData(Uri.fromParts("package", getPackageName(), null));
                                startActivityForResult(intent, requestCode);
                                dialog.dismiss();
                            }
                        });

                        builder.setNegativeButton("取消", null);
                        builder.setCancelable(true);
                        builder.show();
                        return;
                    }
                }
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (polyvPermission.operationHasPermission(requestCode)) {
            gotoActivity(requestCode);
        } else {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("提示");
            builder.setMessage("请开启功能需要的权限，再使用该功能。");
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    dialog.dismiss();
                }
            });

            builder.setCancelable(true);
            builder.show();
        }
    }
}